
#include <Agent.h>
#include <utils.h>
 CTcpServerPtr	*m_pServer;
 CTcpAgentPtr	*m_pAgent;
CTcpAgentListenerImpl::CTcpAgentListenerImpl()
{

}
EnHandleResult CTcpAgentListenerImpl::OnConnect(ITcpAgent *pSender, CONNID dwConnID)
{
	{
		TCHAR szHost[80];
		int iAddressLen = sizeof(szHost) / sizeof(TCHAR);
		USHORT usPort;

		m_Agent->GetRemoteHost(dwConnID, szHost, iAddressLen, usPort);

		LOG_TRACE("OnConnect:%ld %s:$d", dwConnID, szHost, usPort);
	}

	return HR_OK;
}

EnHandleResult CTcpAgentListenerImpl::OnSend(ITcpAgent *pSender, CONNID dwConnID, const BYTE *pData, int iLength)
{
	LOG_TRACE("OnSend:%ld %s:$d", dwConnID, pData, iLength);
	return HR_OK;
}

EnHandleResult CTcpAgentListenerImpl::OnReceive(ITcpAgent *pSender, CONNID dwConnID, const BYTE *pData, int iLength)
{
	LOG_TRACE("OnReceive:%ld %s:$d", dwConnID, pData, iLength);
	TTcpContext *pContext = nullptr;

	m_Agent->GetConnectionExtra(dwConnID, (PVOID *)&pContext);

	if (pContext->serverConnID != 0 && pContext->agentConnID == dwConnID)
		m_Server->Send(pContext->serverConnID, pData, iLength);

	return HR_OK;
}

EnHandleResult CTcpAgentListenerImpl::OnClose(ITcpAgent *pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{

	DetachConnInfo(dwConnID);

	return HR_OK;
}

EnHandleResult CTcpAgentListenerImpl::OnShutdown(ITcpAgent *pSender)
{

	return HR_OK;
}

void CTcpAgentListenerImpl::DetachConnInfo(CONNID dwConnID)
{
	TTcpContext *pContext = nullptr;

	do
	{
		m_Agent->GetConnectionExtra(dwConnID, (PVOID *)&pContext);

		if (pContext)
			break;

		::SwitchToThread();

	} while (!pContext);

	{
		if (pContext->agentConnID == dwConnID)
		{
			pContext->closed = TRUE;
			pContext->agentConnID = 0;

			if (pContext->serverConnID != 0)
				m_Server->Disconnect(pContext->serverConnID);
		}
	}

	pContext->DecRef();
}
